package com.mx.controller;

import com.alibaba.druid.util.StringUtils;
import com.mx.pojo.vo.UserVO;
import com.mx.service.IArticleService;
import com.mx.service.ITagService;
import com.mx.service.IUserService;
import com.mx.service.impl.ArticleServiceImpl;
import com.mx.utils.GraphicHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author MinXu
 * @since 2021/7/28
 * QQ   754647431
 */
@Controller
public class IndexController {
    @Autowired
    ITagService tagService;

    @Autowired
    IArticleService articleService;

    @Autowired
    IUserService userService;

    @GetMapping("/")
    public String index(Integer id, Model model) {
        return "redirect:/type/-1/0";
    }

    @GetMapping("/type/{tid}/{id}")
    public String typePage(@PathVariable Integer tid, @PathVariable Integer id, Model model) {
        // -1代表搜索所有类型的文章 非-1代表该类型的文章
        if (tid == null) {
            tid = -1;
        }
        if (id == null || id <= 0) {
            id = 0;
        }
        ArticleServiceImpl.ArticlePage articlePage = articleService.findTagPage(tid, id);
        model.addAttribute("articles", articlePage.articleVOS);
        model.addAttribute("pages", articlePage.pages);
        model.addAttribute("current", id);
        model.addAttribute("tid", tid);
        model.addAttribute("tags", tagService.findAll());
        return "index";
    }

    @GetMapping("/login")
    public String toLogin(Model model) {
        return "login";
    }

    @PostMapping("/admin")
    public String admin(Model model, String username, String password, String code, HttpSession session) {
        UserVO userVO = userService.verifyUser(username, password);
        if (userVO == null) {
            return "redirect:/login?msg=密码错误";
        }
        if (StringUtils.equals(code, (String) session.getAttribute("code"))) {
            return "redirect:/login?msg=验证码错误";
        }
        return "redirect:/";
    }

    @GetMapping("/code")
    public void yanzhengma(HttpServletResponse resp, @RequestParam("time") Long date, HttpSession session) throws IOException {
        ServletOutputStream outputStream = resp.getOutputStream();
        String code = GraphicHelper.create(outputStream);
        System.out.println("验证码为："+code);
        session.setAttribute("code", code);
        //redisTemplate.opsForValue().set(session.getId(), code, 3, TimeUnit.MINUTES);
    }
}
